//
//  HBBuyingRecordCtrl.m
//  HuoBao
//
//  Created by 于会海 on 15/12/3.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBBuyingRecordCtrl.h"
#import "MJRefresh.h"
#import "HBInvestCtrl.h"
#import "HBInvestManager.h"
#import "HBLoginManager.h"
#import "HBBuyrecordCell.h"
#import "HBBondListCtrl.h"
#import "HBLoginManager.h"
#import "HBGetInvestRecordInfo.h"
#import "HBGetInvestRecordItemInfo.h"
#import "HBGetInvestRecordMonthInfo.h"
#import "HBGetInvestRecordParam.h"
#import "HBGetInvestRecordParser.h"
#import "HBAddBankCtrl.h"

@interface HBBuyingRecordCtrl ()<UITableViewDataSource,UITableViewDelegate>
{
    BOOL            isFirstLogView;
    NSMutableArray* dataSource;
    HBGetInvestRecordInfo* recordInfo;
//    HBGetInvestRecordItemInfo* itemInfo;
//    HBGetInvestRecordMonthInfo* monthInfo;
}
@property (nonatomic, strong) UITableView* myTableView;
@property (nonatomic) NSInteger pageNum;
//下拉的时候才会检测
@property (nonatomic) BOOL isRequestRecordFinish;
@end
@implementation HBBuyingRecordCtrl

#define Notify_buyRecordEndRefresh     @"Notify_buyRecordEndRefresh"
#define GetFinalresult(a,b) (isIphone4or5?a:b)
#define GetFinalResult(x,y,z,r) (IsIphone4?x:(IsIphone6P?r:(IsIphone5?y:z)))

- (void)buildLayout{
    [super buildLayout];
    [self.view setBackgroundColor:[LCCommon getColor:@"e1e1e1"]];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self setExtraCellLineHidden:self.myTableView];
    [self creatUI];
    isFirstLogView = YES;
    _isRequestRecordFinish = NO;
    [self startMJRefresh];
}

- (void)makeBackViewNormal{
    
    UIView* back = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [back setBackgroundColor:[LCCommon getColor:@"e1e1e1"]];
    [self.view addSubview:back];
    
    UIImage* image = [UIImage imageNamed:@"trad_record"];
    UIImageView* normalBack = [[UIImageView alloc] initWithFrame:CGRectMake(0,GetFinalResult(SCREEN_HEIGHT* 30/(667-64-60), SCREEN_HEIGHT* 85/(667-64-60), SCREEN_HEIGHT* 85/(667-64-60), SCREEN_HEIGHT* 85/(667-64-60)), image.size.width, image.size.height)];
    normalBack.image = image;
    normalBack.centerX = self.view.centerX;
    [self.view addSubview:normalBack];
    
    UIButton* button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setFrame:CGRectMake(0, normalBack.origin.y+normalBack.size.height+75, SCREEN_WIDTH - 40, 44)];
    button.centerX = self.view.centerX;
    button.layer.cornerRadius = 4.0;
    [button setTitleColor:[LCCommon getColor:@"ffffff"] forState:UIControlStateNormal];
    [button setBackgroundColor:[LCCommon getColor:@"f34546"]];
    [button setTitle:@"现在就去购买金桔产品" forState:UIControlStateNormal];
    //[self.view addSubview:button];
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonClicked:(UIButton*)button{
    LLog(@"进入购买产品页面");
    if (![HBLoginManager sharedHBLoginManager].hasLogined){
        [HBLoginManager didLoginOut];
        return;
    }
    [CustomLoadingView showHudToView:self.view];
    [HBInvestManager requestToGetUserInvestLimitWithResult:^(BOOL isSuccess, NSString *msg, NSError *error){
        [CustomLoadingView hideHudForView:self.view];
        if (isSuccess){
            if ([[HBInvestManager sharedHBInvestManager].userInvestLimitInfo.bindCardStatus integerValue])
            {
                HBInvestCtrl *investCtrl = [[HBInvestCtrl alloc]init];
                [self.nav pushViewController:investCtrl animated:YES];
            }
            else
            {
                HBAddBankCtrl *checkCtrl = [[HBAddBankCtrl alloc]init];
                checkCtrl.viewpageJumpingFrom = isFromInvestView;
                checkCtrl.isRealName = [[HBInvestManager sharedHBInvestManager].userInvestLimitInfo.identityStatus integerValue];
                [self.nav pushViewController:checkCtrl animated:YES];
            }
        }
        else
        {
            DISSMISS_ERR(error?[error description]:msg);
        }
    }];
}

- (void)startMJRefresh{
    __weak UITableView *tableView = self.myTableView;
    __weak typeof(self) weakSelf = self;
    
    [[NSNotificationCenter defaultCenter]addObserverForName:Notify_buyRecordEndRefresh object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        if (weakSelf.isRequestRecordFinish)
        {
            [tableView.mj_header endRefreshing];
            [tableView reloadData];
        }
    }];
    
    // 下拉刷新
    tableView.mj_header = [HBOrangeHeader headerWithRefreshingBlock:^{
        weakSelf.pageNum = 1;
        
        [weakSelf requestGetInvestRecord];
        
        if (tableView.mj_footer)
        {
            [tableView.mj_footer resetNoMoreData];
        }
        
    }];
    //    tableView.mj_header.backgroundColor = [LCCommon getColor:Main_BackGround_Color];
    tableView.mj_header.automaticallyChangeAlpha = YES;
    
    //    tableView.mj_header.backgroundColor = [LCCommon getColor:Main_BackGround_Color];
    
    // 上拉加载
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        if (recordInfo.dataAry.count>0)
        {
            weakSelf.pageNum++;
            [weakSelf requestGetInvestRecord];
        }
        else
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 结束刷新
                [tableView.mj_footer endRefreshing];
            });
        }
        
    }];
    
//    [self.myTableView.mj_header beginRefreshing];
    
    self.pageNum = 1;
    
    [self requestGetInvestRecord];
}

- (void)requestGetInvestRecord{
    HBGetInvestRecordParam* param = [[HBGetInvestRecordParam alloc] init];
    HBGetInvestRecordParser* parser = [[HBGetInvestRecordParser alloc] init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.pageNum = [NSString stringWithFormat:@"%ld",  (long)self.pageNum];
    [NetCenter getDataFromURL:Method_getInvestRecord params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (myResult.code==0){
            if (myResult.code==0)
            {
                HBGetInvestRecordInfo *info = (HBGetInvestRecordInfo *)myResult.result;
                
                if (self.pageNum==1)
                {
                    recordInfo = info;
                    if (recordInfo.dataAry.count==0)
                    {
                        [self makeBackViewNormal];
                        
                    }
                    
                }
                else
                {
                    [self.myTableView.mj_footer endRefreshing];
                    if (info.dataAry.count>0)
                    {
                        NSMutableArray *dataAry = [NSMutableArray arrayWithArray:recordInfo.dataAry];
                        HBGetInvestRecordMonthInfo *monthInfoOld = [recordInfo.dataAry lastObject];
                        HBGetInvestRecordMonthInfo *monthInfoNew = [info.dataAry firstObject];
                        if ([monthInfoOld.investMonth isEqualToString:monthInfoNew.investMonth])
                        {
                            NSMutableArray *arrayA = [NSMutableArray arrayWithArray:monthInfoOld.investList];
                            [arrayA addObjectsFromArray:monthInfoNew.investList];
                            monthInfoOld.investList = arrayA;
                            [dataAry removeLastObject];
                            [dataAry addObject:monthInfoOld];
                            if (info.dataAry.count>1)
                            {
                                NSMutableArray *arrayB = [NSMutableArray arrayWithArray:info.dataAry];
                                [arrayB removeObjectAtIndex:0];
                                [dataAry addObjectsFromArray:arrayB];
                            }
                            
                        }
                        else
                        {
                            [dataAry addObjectsFromArray:info.dataAry];
                        }
                        recordInfo.dataAry = dataAry;
                        [self.myTableView reloadData];
                    }
                    else
                    {
                        self.pageNum--;
                        [self.myTableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
                
            }
            else
            {
                DISSMISS_ERR(myResult.message);
                if (self.pageNum>1)
                {
                    self.pageNum--;
                    [self.myTableView.mj_footer endRefreshing];
                }
            }
            
            if (self.pageNum==1)
            {
                self.isRequestRecordFinish = YES;
                [[NSNotificationCenter defaultCenter] postNotificationName:Notify_buyRecordEndRefresh object:nil];
            }
        }
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR([error description]);
        if (self.pageNum==1)
        {
            self.isRequestRecordFinish = YES;
            [[NSNotificationCenter defaultCenter] postNotificationName:Notify_buyRecordEndRefresh object:nil];
        }
        else
        {
            self.pageNum--;
            [self.myTableView.mj_footer endRefreshing];
        }
    }];
}

- (void)creatUI{
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-150) style:UITableViewStyleGrouped];
    [self.myTableView setBackgroundColor:[LCCommon getColor:@"E1E1E1"]];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.showsVerticalScrollIndicator = NO;
    self.myTableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.myTableView];
    [self.myTableView registerNib:[UINib nibWithNibName:@"HBBuyrecordCell" bundle:nil] forCellReuseIdentifier:@"recordCell"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isRequestRecordFinish = NO;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    HBGetInvestRecordMonthInfo* monthInfo = recordInfo.dataAry[section];
    LLog(@"%lu",monthInfo.investList.count);
    if (monthInfo.investList > 0) {
        return monthInfo.investList.count;
    }else{
        return 0;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (recordInfo.dataAry.count>0) {
        return recordInfo.dataAry.count;
    }
    return 0;
}

- (void)setExtraCellLineHidden: (UITableView *)tableView{
    
    UIView *view =[ [UIView alloc]init];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
    
    [tableView setTableHeaderView:view];

}

- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString* identifier = @"recordCell";
    HBGetInvestRecordMonthInfo* monthInfo = recordInfo.dataAry[indexPath.section];
    HBGetInvestRecordItemInfo *itemInfo = monthInfo.investList[indexPath.row];
    HBBuyrecordCell*    cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
        if (monthInfo.investList.count>0) {
            itemInfo = (HBGetInvestRecordItemInfo*)monthInfo.investList[indexPath.row];
            cell.tradBank.text = itemInfo.bankName;
            cell.tradDate.text = [LCCommon getMessageTimeStrWithTime:itemInfo.investTime];
            cell.tradMoney.text = [NSString stringWithFormat:@"%.2f",[itemInfo.investMoney doubleValue]];
            cell.tradBankCardNumber.text = itemInfo.bankCardno;
            
            NSString* statusString;
            int  status = [itemInfo.investStatus intValue];
            switch (status) {
                case 1:
                    statusString = @"投资成功";
                    break;
                case 2:
                    statusString = @"投资失败";
                    break;
                case 3:
                    statusString = @"处理中";
                    break;
                    
                default:
                    break;
            }
            cell.tradStatus.text = statusString;
   
        }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 16;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    HBGetInvestRecordMonthInfo* monthInfo ;
    if (recordInfo.dataAry) {
        monthInfo = (HBGetInvestRecordMonthInfo*)recordInfo.dataAry[section];
        return monthInfo.investMonth;
    }else{
        return @"";
    }
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    UIView* footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
    [footView setBackgroundColor:[UIColor clearColor]];
    return footView;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    HBGetInvestRecordMonthInfo* monthInfo ;
    UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-30, 16)];
    [headerView setBackgroundColor:[LCCommon getColor:@"cfcfcf"]];
    UILabel* headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH/2, 16)];
    
    if (recordInfo.dataAry.count>0) {
        monthInfo = (HBGetInvestRecordMonthInfo*)recordInfo.dataAry[section];
        headerLabel.text = monthInfo.investMonth;
    }
    headerLabel.font = [UIFont systemFontOfSize:11];
    headerLabel.textColor = [LCCommon getColor:@"666666"];
    [headerView addSubview:headerLabel];
    return headerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
